# coding:utf-8
import requests
import datetime
import dao.SmsSenMsgDao as SmsSenMsgDao
import time
import xmltodict
import dao.user as userDao
import Util.RedisUtil
import service.QQService  as qqService
from ConfigUtil import configClass

redis = Util.RedisUtil.RedisUtilClass()

configClass = configClass()


def senWxTemplate(data):
    ormMysql = configClass.getItem("urlPath")
    authCode = data['authCode']
    user = userDao.queryUserByAuth(authCode)
    if user is None:
        return resultMsg("-10", "没有找到用户,请关注公众号重试")
    userState = user['userState']
    if '0' != userState:
        return resultMsg("-10", "该用户状态异常,请联系管理员")
    data['userId'] = user['id']
    msg = SmsSenMsgDao.save(data, '0')
    data['url'] = ormMysql['local_host_url'] + "#/showSenMsg?id=" + str(msg.id) + "&authCode=" + authCode
    if 'sendLogo' in data.keys():
        sendLogo = data['sendLogo']
        if '1' == sendLogo:
            return qqService.sen_qq_msg(data, user)

    return sen_wx_msg(data, user)


def sen_wx_msg(data, user):
    token = redis.getByName("token")
    params = {
        'access_token': token
    }
    url = 'https://api.weixin.qq.com/cgi-bin/message/template/send'
    data['operId'] = user['wxOperId']
    r = requests.post(url, params=params, json=getTemplate(data))
    user['currentSenNum'] = user['currentSenNum'] + 1
    user['oneDayNum'] = user['oneDayNum'] + 1
    userDao.UpdateUserById(user)
    json = r.json()
    if 0 == json['errcode']:
        return resultMsg("0", "ok")
    else:
        return resultMsg(json['errcode'], json['errmsg'])


def getUserInfoByOpenId(openId):
    token = redis.getByName("token")
    params = {
        'access_token': token,
        'openid': openId,
        'lang': 'zh_CN'
    }
    url = 'https://api.weixin.qq.com/cgi-bin/user/info'
    return requests.post(url, params=params)


def getTemplate(data):
    template = {
        "touser": data['operId'],
        "template_id": "33FxT1r8_Jo9pKgi4AogKzG3L6war9ATGRGob8ctExE",
        "url": data['url'],
        "data": getData(data['title'], data['content'])
    }
    return template


def getData(title, content):
    if len(content) >= 100:
        content = content[0:97] + '...'
    data = {
        'first': {
            "value": title
        },
        "keyword1": {
            "value": "见后文，来自蓝小喵推送"
        },
        "keyword2": {
            "value": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        },
        "remark": {
            "value": content
        }
    }
    return data


def sendWxTest(json, content):
    result = {
        'xml': {
            'ToUserName': "<![CDATA[" + json['xml']['FromUserName'] + ']]>',
            'FromUserName': '<![CDATA[' + json['xml']['ToUserName'] + ']]>',
            'CreateTime': '<![CDATA[' + str(int(time.time())) + ']]>',
            'MsgType': '<![CDATA[' + 'text' + ']]>',
            'Content': '<![CDATA[' + content + ']]>'
        }
    }
    r = xmltodict.unparse(result, pretty=True)
    r = r.replace('&lt;', '<')
    r = r.replace('&gt;', '>')
    return r


def resultMsg(code, msg):
    return str(
        {
            'code': code,
            'msg': msg
        }
    )
